<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="等级">
        <el-select v-model="form.roleId" placeholder="请选择用户等级">
          <template v-for="role in roles">
            <el-option :label="role.name" :value="role.id"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">Create</el-button>
        <el-button @click="onCancel">Cancel</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { getRoleListAll } from '@/api/role'
  import { saveUser } from '@/api/user'

  export default {
    data() {
      return {
        form: {
          name: '',
          password: '',
          roleId: ''
        },
        roles: {}
      }
    },
    created() {
      getRoleListAll().then(response => {
        this.roles = response.data.content
      })
    },
    methods: {
      onSubmit() {
        saveUser(this.form.name, this.form.password, this.form.roleId).then(response => {
          if (response.code === 1) {
            this.$message('新增成功!')
            this.$router.push({ path: '/sys/user' })
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
      },
      onCancel() {
        this.$router.push({ path: '/sys/user' })
      }
    }
  }
</script>

<style scoped>
  .line {
    text-align: center;
  }
</style>

